package edu.szte.ovrt.datahandler.xml;

import java.io.Writer;

import javax.xml.stream.*;

import edu.szte.ovrt.datahandler.core.AbstractDocumentWriter;
import edu.szte.ovrt.datahandler.core.DocumentWriterException;
import edu.szte.ovrt.datahandler.model.*;

public class XMLWriter extends AbstractDocumentWriter implements XMLConstants {
	protected static final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	XMLStreamWriter xmlWriter;

	public XMLWriter(final Writer writer) throws XMLStreamException {
		super(writer);
		xmlWriter = outputFactory.createXMLStreamWriter(m_writer);
	}

	@Override
	protected void beginDocument(final Document document) throws DocumentWriterException {
		try {
			xmlWriter.writeStartDocument("utf-8", "1.0");
			xmlWriter.writeStartElement("Document");
			xmlWriter.writeDefaultNamespace(NAMESPACE);
		} catch (final XMLStreamException e) {
			throw new DocumentWriterException(e);
		}
	}

	@Override
	protected void beginSection(final Section section) throws DocumentWriterException {
		try {
			xmlWriter.writeStartElement("Section");
			xmlWriter.writeAttribute("name", section.getName());
		} catch (final XMLStreamException e) {
			throw new DocumentWriterException(e);
		}
	}

	@Override
	protected void write(final Item item) throws DocumentWriterException {
		try {
			xmlWriter.writeStartElement("Item");
			xmlWriter.writeAttribute("key", item.getKey());
			xmlWriter.writeAttribute("value", item.getValue());
			xmlWriter.writeEndElement();
		} catch (final XMLStreamException e) {
			throw new DocumentWriterException(e);
		}
	}

	@Override
	protected void endSection(final Section section) throws DocumentWriterException {
		try {
			xmlWriter.writeEndElement();
		} catch (final XMLStreamException e) {
			throw new DocumentWriterException(e);
		}
	}

	@Override
	protected void endDocument(final Document document) throws DocumentWriterException {
		try {
			xmlWriter.writeEndDocument();
		} catch (final XMLStreamException e) {
			throw new DocumentWriterException(e);
		}
	}
}
